import axios from "axios";
import React, { useEffect, useState } from "react";
import { Button, Space, Table, message as antdMessage, Modal } from "antd";
import { deleteConfim } from "../../utils";
const Index = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  // 数据
  const [addressList, setAddressList] = useState([]);
  // 请求函数
  const fetchAddressList = async () => {
    const resp = await axios.get("/api/address/list");
    setAddressList(resp.data.data);
  };
  // 副作用
  useEffect(() => {
    fetchAddressList();
  }, []);

  // 列 数据
  const columns = [
    {
      title: "id",
      dataIndex: "id",
      key: 1,
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: 2,
    },
    {
      title: "地址",
      dataIndex: "address",
      key: 3,
    },
    {
      title: "电话",
      dataIndex: "tel",
      key: 4,
    },
    {
      title: "操作",
      key: 5,
      // 自定义渲染
      render(_) {
        return (
          <Space>
            <Button type="primary">编辑</Button>
            <Button
              type="primary"
              danger
              onClick={() =>
                deleteConfim("警告", "确认要删除吗", () => handleDelete(_))
              }
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];
  // 单个 删除函数
  const handleDelete = async (_) => {
    const resp = await axios.delete("/api/address/list", {
      params: { id: _.id },
    });
    const { code, message } = resp.data;
    if (code === 200) {
      antdMessage.success(message);
      fetchAddressList();
    }
  };
  // 选中 删除函数
  const handleDeleteSelected = async () => {
    const requests = selectedRowKeys.map(v => {
      return axios.delete('/api/address/list', { params: { id: v } })
    })
    await Promise.all(requests);
    fetchAddressList()
  };

  return (
    <div>
      <div className="opraion">
        <Button
          type="primary"
          danger
          onClick={() =>
            deleteConfim("警告", "确定删除选中的数据吗？", () =>
              handleDeleteSelected()
            )
          }
        >
          删除所选
        </Button>
      </div>
      <Table
        scroll={{ y: 550 }}
        dataSource={addressList}
        columns={columns}
        rowKey={"id"}
        rowSelection={{
          onChange(selectedRowKeys) {
            setSelectedRowKeys(selectedRowKeys);
          },
        }}
      ></Table>
    </div>
  );
};

export default Index;
